package com.hung.triple.transport.netty4.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import javax.net.ssl.SSLSession;
import javax.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Hung
 * @date 2022/11/24 15:59
 */
public class NettyChannelSslHandler extends ChannelDuplexHandler {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
                (GenericFutureListener<Future<Channel>>) future -> {
                    if (future.isSuccess()) {
                        System.out.println("握手成功");

                        SSLSession ss = ctx.pipeline().get(SslHandler.class).engine().getSession();
                        System.out.println("cipherSuite:" + ss.getCipherSuite());
                        X509Certificate cert = ss.getPeerCertificateChain()[0];
                        String info;
                        // 获得证书版本
                        info = String.valueOf(cert.getVersion());
                        System.out.println("证书版本:" + info);
                        // 获得证书***
                        info = cert.getSerialNumber().toString(16);
                        System.out.println("证书***:" + info);
                        // 获得证书有效期
                        Date beforedate = cert.getNotBefore();
                        info = new SimpleDateFormat("yyyy/MM/dd").format(beforedate);
                        System.out.println("证书生效日期:" + info);
                        Date afterdate = cert.getNotAfter();
                        info = new SimpleDateFormat("yyyy/MM/dd").format(afterdate);
                        System.out.println("证书失效日期:" + info);
                        // 获得证书主体信息
                        info = cert.getSubjectDN().getName();
                        System.out.println("证书拥有者:" + info);
                        // 获得证书颁发者信息
                        info = cert.getIssuerDN().getName();
                        System.out.println("证书颁发者:" + info);
                        // 获得证书签名算法名称
                        info = cert.getSigAlgName();
                        System.out.println("证书签名算法:" + info);

                    } else {
                        System.out.println("握手失败");
                    }
                });

        SocketChannel channel = (SocketChannel) ctx.channel();
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " conn:");
        System.out.println("IP:" + channel.localAddress().getHostString());
        System.out.println("Port:" + channel.localAddress().getPort());

        super.channelActive(ctx);
    }
}
